<html lang="en">
	<head>
		<meta charset="UTF-8">
		<title>bin文件转base64编码</title>
	</head>
	<body>
		<h>bin文件转base64编码</h>
		<br /><br />
		<label class="firmware">
          	<input type="file" accept=".bin" />
        </label>
        <div style="position:absolute; top: 100px;width: 100%;bottom: 0px;">
			<div id="document" style="height: 100%;width: 100%;"></div>
		</div>
        <script type="text/javascript">
			function fakeClick(obj) {
			    var ev = document.createEvent("MouseEvents");
			    ev.initMouseEvent(
			        "click", true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null
			    );
			    obj.dispatchEvent(ev);
			}

			function download(name, data) {
			    var urlObject = window.URL || window.webkitURL || window;

			    var downloadData = new Blob([data]);

			    var save_link = document.createElementNS("http://www.w3.org/1999/xhtml", "a")
			    save_link.href = urlObject.createObjectURL(downloadData);
			    save_link.download = name;
			    fakeClick(save_link);
			}

			function arrayBufferToBase64(buffer) {
			 	var binary = '';
			 	var bytes = new Uint8Array(buffer);
			 	var len = bytes.byteLength;
			 	for (var i = 0; i < len; i++) {
			       	binary += String.fromCharCode(bytes[i]);
			 	}
			 	return window.btoa(binary);
			}
			const input = document.querySelector('input');
			input.addEventListener('change', getBase64);

			async function getBase64() {
				const readUploadedFileAsText = (inputFile) => {
			    	const reader = new FileReader();

			    	return new Promise((resolve, reject) => {
				      	reader.onerror = () => {
				        	reader.abort();
				        	reject(new DOMException("Problem parsing input file."));
				      	};

				      	reader.onload = () => {
				        	resolve(reader.result);
				      	};
				      	reader.readAsText(inputFile);
			    	});
			  	};

			  	let binfile = input.files[0];
			  	if (binfile) {
				    let contents = await readUploadedFileAsText(binfile);
				    document.getElementById("document").innerHTML = contents;
	      			//download(binfileName + "(base64编码).txt", arrayBufferToBase64(contents));
	      		}
			}
		</script>
	</body>
</html>